﻿$(function () {
    //初始化日期控件
    InitDateTimePicker();
    //初始化图标选择控件
    $('select.chosen-icons').chosenIcons();
})

function GetRootPath() {
    var loc = window.location,
        host = loc.hostname,
        protocol = loc.protocol,
        port = loc.port ? (':' + loc.port) : '';
    var path = location.pathname;

    if (path.indexOf('/') === 0) {
        path = path.substring(1);
    }

    var mypath = '/' + path.split('/')[0];
    path = (mypath != undefined ? mypath : ('/' + loc.pathname.split('/')[1])) + '/';

    var rootPath = protocol + '//' + host + port + path;
    return rootPath;
}

function GetProjectName() {
    var loc = window.location,
        host = loc.hostname,
        protocol = loc.protocol,
        port = loc.port ? (':' + loc.port) : '';
    var path = location.pathname;
    return path;
}

function GetUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

function CloudAjax(sync, cache, type, processData, url, contenttype, data, success, error, before) { //封装ajax的一些常用参数  //data数据可以为空
    $.ajax({
        sync: sync,
        cache: cache,
        type: type,
        url: url,
        contentType: contenttype,
        processData: processData,
        data: data,
        headers: {
            //"Authorization":$.cookie('token')
        },
        beforSend: function (request) {
            if (before) {
                before()
            }
        },
        error: function (data) {
            if (error) {
                error(data);
            }
        },
        complete: function (data, status) {

        },
        success: function (data) {
            if (success) {
                success(data)
            }
        }
    });
}

function CloudPost(data, url, success) {
    CloudAjax("true", "false", "POST", true, url, "application/x-www-form-urlencoded; charset=UTF-8", data, success)
}

function CloudPostFile(data, url, success) {
    CloudAjax("true", "false", "POST", false, url, false, data, success)
}

function CloudGet(url, success) {
    CloudAjax("true", "false", "GET", true, url, "application/x-www-form-urlencoded; charset=UTF-8", "", success)
}

var Base64 = {
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    Encode: function (e) {
        var t = "";
        var n, r, i, s, o, u, a;
        var f = 0;
        e = Base64._utf8_encode(e);
        while (f < e.length) {
            n = e.charCodeAt(f++);
            r = e.charCodeAt(f++);
            i = e.charCodeAt(f++);
            s = n >> 2;
            o = (n & 3) << 4 | r >> 4;
            u = (r & 15) << 2 | i >> 6;
            a = i & 63;
            if (isNaN(r)) {
                u = a = 64
            } else if (isNaN(i)) {
                a = 64
            }
            t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
        }
        return t
    },
    Decode: function (e) {
        var t = "";
        var n, r, i;
        var s, o, u, a;
        var f = 0;
        e = e.replace(/[^A-Za-z0-9+/=]/g, "");
        while (f < e.length) {
            s = this._keyStr.indexOf(e.charAt(f++));
            o = this._keyStr.indexOf(e.charAt(f++));
            u = this._keyStr.indexOf(e.charAt(f++));
            a = this._keyStr.indexOf(e.charAt(f++));
            n = s << 2 | o >> 4;
            r = (o & 15) << 4 | u >> 2;
            i = (u & 3) << 6 | a;
            t = t + String.fromCharCode(n);
            if (u != 64) {
                t = t + String.fromCharCode(r)
            }
            if (a != 64) {
                t = t + String.fromCharCode(i)
            }
        }
        t = Base64._utf8_decode(t);
        return t
    },
    _utf8_encode: function (e) {
        e = e.replace(/rn/g, "n");
        var t = "";
        for (var n = 0; n < e.length; n++) {
            var r = e.charCodeAt(n);
            if (r < 128) {
                t += String.fromCharCode(r)
            } else if (r > 127 && r < 2048) {
                t += String.fromCharCode(r >> 6 | 192);
                t += String.fromCharCode(r & 63 | 128)
            } else {
                t += String.fromCharCode(r >> 12 | 224);
                t += String.fromCharCode(r >> 6 & 63 | 128);
                t += String.fromCharCode(r & 63 | 128)
            }
        }
        return t
    },
    _utf8_decode: function (e) {
        var t = "";
        var n = 0;
        var r = c1 = c2 = 0;
        while (n < e.length) {
            r = e.charCodeAt(n);
            if (r < 128) {
                t += String.fromCharCode(r);
                n++
            } else if (r > 191 && r < 224) {
                c2 = e.charCodeAt(n + 1);
                t += String.fromCharCode((r & 31) << 6 | c2 & 63);
                n += 2
            } else {
                c2 = e.charCodeAt(n + 1);
                c3 = e.charCodeAt(n + 2);
                t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
                n += 3
            }
        }
        return t
    }
}

function UUID() {
    var date = new Date();
    return DateToString(date) + 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

function DateToString(now) {
    var year = now.getFullYear();
    var month = (now.getMonth() + 1).toString();
    var day = (now.getDate()).toString();
    var hour = (now.getHours()).toString();
    var minute = (now.getMinutes()).toString();
    var second = (now.getSeconds()).toString();
    if (month.length == 1) {
        month = "0" + month;
    }
    if (day.length == 1) {
        day = "0" + day;
    }
    if (hour.length == 1) {
        hour = "0" + hour;
    }
    if (minute.length == 1) {
        minute = "0" + minute;
    }
    if (second.length == 1) {
        second = "0" + second;
    }
    var dateTime = year + month + day + hour + minute + second;
    return dateTime;
}

$.fn.extend({
    // 调用方式：$("xxxxx").getform();
    GetForm: function () {
        var obj = {};
        var array = $(this).serializeArray();
        $.each(array, function () {
            obj[this.name] = this.value;
        });
        return obj;
    },
    // 调用方式： $("xxx").setform(json);
    // $("标签x").setform(json数据); 给标签x内文本框自动赋值json数据
    //$("#div").setform(${jsondata}); json格式 : {"name":"1","sax":"2","checkbox":"1,2,3"}
    SetForm: function (jsonValue) {
        if (typeof (jsonValue) != "undefined") {
            var obj = this;
            $.each(jsonValue, function (name, ival) {
                var $input = obj.find("input[name='" + name + "']");
                if ($input) {
                    if ($input.attr("type") == "radio" || $input.attr("type") == "checkbox") {
                        $input.each(function () {
                            if (Object.prototype.toString.apply(ival) == '[object String]') { // [object String] 或者 [object Array]
                                var arr = new Array();
                                arr = ival.split(","); //字符串分割 
                                for (var i = 0; i < arr.length; i++) {
                                    if ($(this).val() == arr[i]) {
                                        $(this).attr("checked", "checked");
                                    }
                                }
                            } else {
                                if ($(this).val() == ival) {
                                    $(this).attr("checked", "checked");
                                }
                            }
                        });
                    } else if ($input.attr("type") == "textarea") { // 多行文本框  
                        obj.find("[name=" + name + "]").html(ival);
                    } else {
                        obj.find("[name=" + name + "]").val(ival);
                    }
                }
                var $select = obj.find("select[name='" + name + "']");
                if ($select) {
                    if ($select.hasClass("chosen-icons")) {
                        $select.val(ival).change();
                    } else {
                        $select.val(ival)
                    }

                }
            });

        }
    },
    // 调用方式： $("xxx").disform(yyy); 标签disabled:true,yyy为disabled:false
    // $("标签x").setform(标签y); 除标签y以外,禁用标签x内全部文本只读,标签y可以为空
    //$("#disform").disform(); 
    //$("#disform").disform("#div");
    DisForm: function (jsonValue) {
        var obj = this;
        $("#" + obj[0].id + " input").each(function () {
            this.disabled = true
            this.style.backgroundColor = "#dcdcdc";
        })
        $("#" + obj[0].id + " textarea").each(function () {
            this.disabled = true
            this.style.backgroundColor = "#dcdcdc";
        })
        $("#" + obj[0].id + " select").each(function () {
            this.disabled = true
            this.style.backgroundColor = "#dcdcdc";
        })
        if (jsonValue != '') {
            $(jsonValue + " input").each(function () {
                this.disabled = false
                this.style.backgroundColor = "#ffffff";
            })
            $(jsonValue + " textarea").each(function () {
                this.disabled = false
                this.style.backgroundColor = "#ffffff";
            })
            $(jsonValue + " select").each(function () {
                this.disabled = false
                this.style.backgroundColor = "#ffffff";
            })
        }
    },
    //$("标签x").disformtrue(); 标签x内全部元素解除只读状态
    //$("#text_essas").disformtrue(); 
    DisFormTrue: function () {
        var obj = this;
        $("#" + obj[0].id + " input").each(function () {
            this.disabled = false
            this.style.backgroundColor = "#ffffff";
        })
        $("#" + obj[0].id + " textarea").each(function () {
            this.disabled = false
            this.style.backgroundColor = "#ffffff";
        })
        $("#" + obj[0].id + " select").each(function () {
            this.disabled = false
            this.style.backgroundColor = "#ffffff";
        })
    }
})

function BindMenuTree(TreeID, zTreeNodes, zTreeOnClick) {
    var setting = {
        data: {
            simpleData: {
                enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式 
                idKey: "id",   //节点数据中保存唯一标识的属性名称
                pIdKey: "pid",    //节点数据中保存其父节点唯一标识的属性名称 
                rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            },
            key: {
                name: "name"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
            },
        },
        callback: {

        }
    };
    if (zTreeOnClick) {
        setting.callback.onClick = zTreeOnClick
    }
    zTreeObj = $.fn.zTree.init($("#" + TreeID), setting, zTreeNodes);
}

function InitDateTimePicker() {
    $(".form-date").datetimepicker(
        {
            language: "zh-CN",
            weekStart: 1,
            todayBtn: 1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            minView: 2,
            forceParse: 0,
            format: "yyyy-mm-dd"
        });
    $(".form-time").datetimepicker({
        language: "zh-CN",
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 1,
        minView: 0,
        maxView: 1,
        forceParse: 0,
        format: 'hh:ii'
    });
    $(".form-datetime").datetimepicker(
        {
            weekStart: 1,
            todayBtn: 1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            forceParse: 0,
            showMeridian: 1,
            format: "yyyy-mm-dd hh:ii"
        });
}


